package com.cpkso.taobao.taobao11client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.swing.JButton;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.LoadURLParams;
import com.teamdev.jxbrowser.chromium.dom.By;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;

/**
 * @author wrzhxy@qq.com
 * @date 2018年5月5日
 * 买家客户端
 */
public class BuyerClient {
	// PAID SUCCESS SEND
	final static int PAGE_SIZE = 15; 		// 每个请求获取最大500条数据
	static String username = null;
	final private static String BUYER_ORDER_LIST = "https://buyertrade.taobao.com/trade/itemlist/asyncBought.htm?action=itemlist/BoughtQueryAction&event_submit_do_query=1&_input_charset=utf8";
	final private static String BUYER_ORDER_PAGE = "https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm";
	// 120.27.39.105:9090/user/all
	final private static String BUYER_URL = "http://120.27.39.105:9090/order/b";
//	final private static String BUYER_URL = "http://localhost:9090/order/b";
	final private static String PAID = "PAID";
	final private static String SUCCESS = "SUCCESS";
	final private static String SEND = "SEND";
	// 买家号
    final public static void buyer(String username) {
    	BuyerClient.username = username;
//    	BrowserPreferences.setChromiumSwitches("--remote-debugging-port=9222");
    	
    	Browser browser = new Browser();
//    	// 返回谷歌开发者页面
//    	String remoteDebuggingURL = browser.getRemoteDebuggingURL();
    	
    	BrowserView view = new BrowserView(browser);
        
        // 设置获取订单的时间
        final JButton getOrderBtn = new JButton();
        
        getOrderBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	// 订单列表	
            	List<TbSBOrderVo> orders = new ArrayList<>();
            	List<String> curstatus = new ArrayList<>();
        		curstatus.add(PAID);
        		
            	// 根据订单时间判断是否从当前时间往前推一个月的 - 不必，因为发送的请求带有筛选条件
            	// 获取当前时间
            	Date now = new Date();
            	long nowLong = now.getTime();
            	// 2018-01-21 15:01:14
//            	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	// 获取一个月前的时间
            	Calendar dataCalculate = Calendar.getInstance();
            	dataCalculate.setTime(now);
            	// 减掉一个月
            	dataCalculate.add(Calendar.MONTH, -1);
            	// 获取一个月前的时间
            	Date oneMonthAgo = dataCalculate.getTime();
            	long oneMonthAgoLong = oneMonthAgo.getTime();
            	
            	// 页码，如果头500不够就翻页
            	int pageNo = 1;
            	List<Integer> pageNoStore = new ArrayList<>();
            	pageNoStore.add(pageNo);
            	
            	// 发送请求获取信息
            	sendAsncRequest(browser, oneMonthAgoLong, nowLong, pageNo, PAGE_SIZE, curstatus.get(0));
            	Random random = new Random();
            	
            	browser.addLoadListener(new LoadAdapter() {
                    @Override
                    public void onFinishLoadingFrame(FinishLoadingEvent event) {
                        if (event.isMainFrame()) {
                        	// 页面加载完成后等一下再发送搜索请求
                        	int rand = random.nextInt() % 2 + 2;
                        	for (int i = 0; i < rand; i++) {
                        		App.sleep();
                        	}
                        	String strUndealData = browser.getDocument().getDocumentElement().findElement(By.tagName("body")).getInnerHTML();
                            
                            // 封装进json object
                    		JSONObject jsonUndealData = new JSONObject(strUndealData);
                    		// 获取mainOrders
                    		JSONArray mainOrders = jsonUndealData.getJSONArray("mainOrders");
                    		// 判断mainOrders是否为空[]
                    		
                        	// 获取当天的订单
                        	// 获取一个月的订单
                    		// 判断时间
                    		// 设置最大数量500个尽量一次取完
                    		// 如果没有取完，就翻页
                    		// 遍历 获取数据
                    		for (int i = 0; i < mainOrders.length(); i++) {
                    			TbSBOrderVo order = generateOrder(mainOrders, i);
System.out.println("单条数据" + i + " : " + order);
                    		    orders.add(order);
                    		}
                    		// 判断最后一条记录是不是第500，如果是继续翻页
                    		
                            if (mainOrders.length() >= PAGE_SIZE) {
                            	App.sleep();
                            	nextPage(browser, pageNoStore, oneMonthAgoLong, nowLong, curstatus.get(0));
                            } else {
                            	// 说明已经获取完毕
                            	// TODO 将数据全部发送出去
                            	// 将数据全部发送出去
System.out.println("\n\n\n--------------------------------------------" + curstatus.get(0) + " -- " + orders.size());
                            	if (!curstatus.get(0).equals(SUCCESS)) {
									if (curstatus.get(0).equals(PAID)) {
										curstatus.set(0, SEND);
									} else {
										curstatus.set(0, SUCCESS);
									}
                            		pageNoStore.set(0, 0);
                            		nextPage(browser, pageNoStore, oneMonthAgoLong, nowLong, curstatus.get(0));
                            	} else {
                            		orders.sort(new OrderComparator());
                            		sendData(orders, BUYER_URL, username);
                            		browser.executeJavaScript("alert(\"获取数据成功!\");");
                            	}
                            }
                        }
                    }
            	});
            	
            }
            
	        
        });
        
        App.initalFrame(view, getOrderBtn, "买家号客户端");

        browser.loadURL(BUYER_ORDER_PAGE);

//        // 谷歌调试器窗口
//        Browser browser2 = new Browser();
//        BrowserView browserView2 = new BrowserView(browser2);
//
//        JFrame frame2 = new JFrame();
//        frame2.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//        frame2.add(browserView2, BorderLayout.CENTER);
//        frame2.setSize(700, 500);
//        frame2.setLocationRelativeTo(null);
//        frame2.setVisible(true);
//
//        browser2.loadURL(remoteDebuggingURL);
    }
 // 发送异步请求获取买家订单数据
    static public void sendAsncRequest(Browser browser, long beginDate, long endDate, int pageNo, int pageSize, String status) {
System.out.println("status: " + status);	    		
		browser.loadURL(new LoadURLParams(BUYER_ORDER_LIST,
					"&auctionStatus=" + status
    				+ "&dateBegin=" + beginDate
    				+ "&dateEnd=" + endDate
    				+ "&pageNum=" + pageNo
    				+ "&pageSize=" + pageSize
    				+ "&prePageNo=1",
					"Accept:application/json, text/javascript, */*; q=0.01\n"
					+ "Accept-Encoding:gzip, deflate, br\n"
					+ "Accept-Language:zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2\n"
//					+ "Content-Length:101\n" //Your browser sent a request that this server could not understand 长度不对，所以服务器不理解
					+ "Content-Type:application/x-www-form-urlencoded; charset=UTF-8\n"
					+ "Connection:keep-alive\n"
					+ "Origin:https://buyertrade.taobao.com\n"
					+ "Referer:https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm\n"
					+ "Save-Data:on\n"
					+ "User-Agent:Mozilla/5.0 (Windows NT 6.1; rv:59.0) Gecko/20100101 Firefox/59.0\n"
					+ "X-Requested-With:XMLHttpRequest\n"));
	}

	/**
	 * 将订单数据发送出去
	 */
	// 用户名
//	private final String USERNAME = Property.getProperty("username");
	static public void sendData(List<TbSBOrderVo> orders, String url, String username) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		// 发送Post请求
		HttpPost httpPost = new HttpPost(url);
		// 模拟json数据
		// TODO jsonObject 还是 jsonArray
		JSONArray js = new JSONArray(orders);
//System.out.println("最终json数据：" + js.toString());
		// 将Json数据放入StringEntity作为载体给httpPost来发送，所有数据要发送都要放入各种HttpClient定义的Entity实例中
		StringEntity se = null;
		// TODO charset去掉
		se = new StringEntity(js.toString(), Charset.forName("UTF-8"));
		se.setContentEncoding("UTF-8");
		se.setContentType("application/json");
//    		httpPost.addHeader("Content-type", "application/json;charset=utf-8");
//    		httpPost.addHeader("Accept", "application/json");
		httpPost.setEntity(se);
		// 开始发送请求并拿到响应
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpPost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			// 打印状态码
//System.out.println("状态码：" + response.getStatusLine());
			
			System.out.println("发送成功:" + js.length());
			// 
			HttpEntity entity = response.getEntity();
			// do something useful with the response body
			// and ensure it is fully consumed
			EntityUtils.consume(entity);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	static public TbSBOrderVo generateOrder(JSONArray mainOrders, int i) {
		// 提取订单内容
		JSONObject orderDetail = mainOrders.optJSONObject(i);
		JSONObject orderInfo = orderDetail.getJSONObject("orderInfo");
		// 下单时间
		String createTimeStr = orderInfo.getString("createTime");
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date createTime = null;
		try {
			createTime = sdf.parse(createTimeStr);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		// 订单id
		String id = orderInfo.getString("id");
		
		// 订单金额
		JSONObject payInfo = orderDetail.getJSONObject("payInfo");
		Double actualFee = payInfo.getDouble("actualFee");
		
		// 产品名
		// 子订单 包括运费险
		JSONArray subOrder = orderDetail.getJSONArray("subOrders");
		List<String> items = new ArrayList<>();
		for (int j = 0; j < subOrder.length(); j++) {
			JSONObject singleSubOrder = subOrder.optJSONObject(j);
			JSONObject subItemInfo = singleSubOrder.getJSONObject("itemInfo");
			String title = subItemInfo.getString("title");
			items.add(title);
		}
		TbSBOrderVo order = new TbSBOrderVo(id, "", createTime.getTime(), actualFee, items, username);
		return order;
	}
	
	static public void nextPage(Browser browser, List<Integer> pageNoStore, Long oneMonthAgoLong, Long nowLong, String status) {
		// 继续翻页
		Integer pageNo = pageNoStore.get(0);
		pageNo++;
		pageNoStore.set(0, pageNo);
		sendAsncRequest(browser, oneMonthAgoLong, nowLong, pageNo, PAGE_SIZE, status);
	}
}
